<?php

include_once ('cometchat_init.php');
$response = array();
$messages = array();
if (!$user['is_guest'])
{
    if (!empty($_POST['chatbox']))
    {
        if (!empty($_SESSION['cometchat_user_' . $_POST['chatbox']]))
        {
            $messages = $_SESSION['cometchat_user_' . $_POST['chatbox']];
        }
    }
    else
    {
        if (!empty($_POST['buddylist']) && $_POST['buddylist'] == 1)
        {
            getBuddyList();
        }
        if (!empty($_POST['initialize']) && $_POST['initialize'] == 1)
        {
            getStatus();
            if (!empty($_SESSION['cometchat_sessionvars']))
            {
                $response['initialize'] = $_SESSION['cometchat_sessionvars'];
                if (!empty($_SESSION['cometchat_sessionvars']['openChatboxId']) && !empty($_SESSION['cometchat_user_' . $_SESSION['cometchat_sessionvars']['openChatboxId']]))
                {
                    $messages = array_merge($messages, $_SESSION['cometchat_user_' . $_SESSION['cometchat_sessionvars']['openChatboxId']]);
                }
            }
        }
        else
        {
            if (empty($_SESSION['cometchat_sessionvars']))
            {
                $_SESSION['cometchat_sessionvars'] = array();
            }
            if (!empty($_POST['sessionvars']))
            {
                ksort($_POST['sessionvars']);
            }
            else
            {
                $_POST['sessionvars'] = '';
            }
            if (!empty($_POST['updatesession']) && $_POST['updatesession'] == 1)
            {
                $_SESSION['cometchat_sessionvars'] = $_POST['sessionvars'];
            }
            if ($_SESSION['cometchat_sessionvars'] != $_POST['sessionvars'])
            {
                $response['updatesession'] = $_SESSION['cometchat_sessionvars'];
            }
        }
        getLastTimestamp();
        fetchMessages();
    }
    $db->updateRow('bbs_members', array('uid' => $uid), array('lastactivity' => getTime()));
}
else
{
    $response['loggedout'] = '1';
    session_destroy();
}
function getStatus()
{
    global $response;
    global $uid;
    global $db;
    $chat = $db->getRow("
		SELECT message, status 
		FROM cometchat_status 
		WHERE userid = %1", $uid);
    if (empty($chat['status']))
    {
        $chat['status'] = 'available';
    }
    else
    {
        if ($chat['status'] == 'offline')
        {
            $_SESSION['cometchat_sessionvars']['buddylist'] = 0;
        }
    }
    if (empty($chat['message']))
    {
        $chat['message'] = "I'm " . ucfirst($chat['status']);
    }
    $status = array('message' => $chat['message'], 'status' => $chat['status']);
    $response['userstatus'] = $status;
}
function getLastTimestamp()
{
    global $db;
    if (empty($_POST['timestamp']))
    {
        $_POST['timestamp'] = 0;
    }
    if ($_POST['timestamp'] == 0)
    {
        foreach ($_SESSION as $key => $value)
        {
            if (substr($key, 0, 15) == "cometchat_user_")
            {
                $temp = end($_SESSION[$key]);
                if ($_POST['timestamp'] < $temp['id'])
                {
                    $_POST['timestamp'] = $temp['id'];
                }
            }
        }
        if ($_POST['timestamp'] == 0)
        {
            $chat = $db->getRow("select id from cometchat order by id desc limit 1");
            $_POST['timestamp'] = $chat['id'];
        }
    }
}
function getBuddyList()
{
    global $response;
    global $uid;
    global $db;
    $time = getTime();
    if ((empty($_SESSION['cometchat_buddytime'])) || ($_POST['initialize'] == 1) || (!empty($_SESSION['cometchat_buddytime']) && ($time - $_SESSION['cometchat_buddytime'] > REFRESH_BUDDYLIST)))
    {
        $request = $db->query("
			SELECT m.uid, 
				m.realname, 
				m.lastactivity, 
				s.message, 
				s.status 
			FROM bbs_buddy b
			LEFT JOIN bbs_members m 
			ON m.uid = b.friendid 
			LEFT JOIN cometchat_status s 
			ON m.uid = s.userid 
			WHERE b.uid = %1 
			ORDER by m.username ASC
		", $uid);
        if (!empty($request))
        {
            foreach ($request as $chat)
            {
                if ((($time - $chat['lastactivity']) < ONLINE_TIMEOUT) && $chat['status'] != 'invisible' && $chat['status'] != 'offline')
                {
                    if ($chat['status'] != 'busy')
                    {
                        $chat['status'] = 'available';
                    }
                }
                else
                {
                    $chat['status'] = 'offline';
                }
                if ($chat['message'] == null)
                {
                    $chat['message'] = "I'm " . ucfirst($chat['status']);
                }
                $chat['username'] = $chat['realname'];
                $buddyList[] = array('id' => $chat['uid'], 'name' => $chat['username'], 'status' => $chat['status'], 'message' => $chat['message'], 'time' => $chat['lastactivity']);
            }
        }
        $_SESSION['cometchat_buddytime'] = $time;
        if (!empty($buddyList))
        {
            $response['buddylist'] = $buddyList;
        }
    }
}
function fetchMessages()
{
    global $response;
    global $uid;
    global $db;
    global $messages;
    $timestamp = 0;
    $request = $db->query("
		SELECT cometchat.id, 
			cometchat.from, 
			cometchat.to, 
			cometchat.message, 
			cometchat.sent, 
			cometchat.read 
		FROM cometchat 
		WHERE (cometchat.to = %1 
		OR cometchat.from = %1 ) 
		AND (cometchat.id > %2 
		OR (cometchat.to = %1 
		AND cometchat.read != 1)) 
		ORDER by cometchat.id
	", $uid, $_POST['timestamp']);
    if (!empty($request))
    {
        foreach ($request as $chat)
        {
            $self = 0;
            $old = 0;
            if ($chat['from'] == $uid)
            {
                $chat['from'] = $chat['to'];
                $self = 1;
                $old = 1;
            }
            $messages[] = array('id' => $chat['id'], 'from' => $chat['from'], 'message' => $chat['message'], 'self' => $self, 'old' => $old);
            if ($self == 0 && $old == 0 && $chat['read'] != 1)
            {
                $_SESSION['cometchat_user_' . $chat['from']][] = array('id' => $chat['id'], 'from' => $chat['from'], 'message' => $chat['message'], 'self' => 0, 'old' => 1);
            }
            $timestamp = $chat['id'];
        }
    }
    if (!empty($messages))
    {
        $db->query("
			UPDATE cometchat 
			SET cometchat.read = '1' 
			WHERE cometchat.to = %1 
			AND cometchat.id <= %2", $uid, $timestamp);
    }
}
if (!empty($messages))
{
    $response['messages'] = $messages;
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($response);
exit;
